﻿///<reference path="/Scripts/References.js" />

//-----------------------------------------------------------------------------------
//Uses Advanced JavaScript outlining for Visual Studio 11 to activate Region handling
//-----------------------------------------------------------------------------------

/*#region Default values*/
var dialogCounter = 8000;//Next dialog z-index

var defaultDialogWidth = 800;
var defaultDialogHeight = 600;

var defaultSmallDialogWidth = 450;
var defaultSmallDialogHeight = 200;

var dlgCompetencyWidth = 400;
var dlgCompetencyHeight = 150;

var dlgTelecomWidth = 600;
var dlgTelecomHeight = 150;

var dlgAddressWidth = 650;
var dlgAddressHeight = 350;

var dlgChangePasswordWidth = 400;
var dlgChangePasswordHeight = 400;

var dlgLookupFormWidth = 400;
var dlgLookupFormHeight = 175;

var waitImage = "<div class=\"k-loading-image\"></div>";


/*#endregion*/

/*#region globals*/
var language;
var tLanguages;

/*KendoUIDataSources*/
var ProfileDetailCompetenciesDataSource;
/*#end region*/

/*#region DateTimePicker default options*/
$.timepicker.regional['fr'] = {
    timeOnlyTitle: 'Heure',
    timeText: 'Heure',
    hourText: 'Heure',
    minuteText: 'Minute',
    secondText: 'Secondes',
    millisecText: 'Milliseconde',
    timezoneText: 'Fuseau',
    currentText: 'Maintenant',
    closeText: 'Fermer',
    timeFormat: 'HH:mm:ss',
    amNames: ['AM', 'MA'],
    pmNames: ['PM', 'AM'],
    isRTL: false
};

/*#endregion*/
var MyProfileAddresses;
var CurrentAddressChanged;
var CurrentTelecomChanged;
var CurrentCompetencyChanged;
var CurrentAddressId;
var CurrentTelecomId;
var CurrentCompetencyId;
var MyProfileChanged;
var MyProfileMap;
var MyProfileMapMarker;
var ForUserId;

/*#region Core common*/

$.fn.MainAjaxSuccess = function (a, b, c) {
    /// <summary>
    /// [INNOVACALL Framework specific] Method called when an MVC.ajax form post succeed
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <param name="c"></param>
    if (a.success) {
        if (a.scriptToExecute != null) {
            eval(a.scriptToExecute);
        }
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}


$.fn.MainAjaxFailure = function (a, b, c) {
    /// <summary>
    /// [INNOVACALL Framework specific] Method called when an MVC.ajax form post fails
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <param name="c"></param>
    if (a.scriptToExecute != null) {
        if (a.scriptToExecute != "") {
            eval(a.scriptToExecute);
        }
    } else {
        $.fn.jqDialogAjaxError(b + " " + a.status + ":" + a.statusText, a.responseText, "", 600, 400);
    }
}

/*#endregion*/

$.fn.LookupDialogOpenClick = function (evt, ui) {
    /// <summary>
    /// Generic method to load lookup management generic
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var listrole = $(evt.currentTarget).data("listrole");
    var itemrole = $(evt.currentTarget).data("itemrole");
    var onClose = $(evt.currentTarget).data("onclose");
    var dialogTitle = eval("cap_EtyName_" + listrole);
    $.fn.jqDialogContainer("divDialogLookup", dialogTitle, $.fn.LookupBuildGrid, onClose, 500, 545, "<div id='LookupDialogGridDiv' data-listrole='" + listrole + "' data-itemrole='" + itemrole + "'></div>");
}

$.fn.LookupBuildGrid = function () {
    /// <summary>
    /// Build grid for a lookup
    /// </summary>
    var dialog = $("#LookupDialogGridDiv");
    var listrole = dialog.data("listrole");
    var itemrole = dialog.data("itemrole");
    dialog.css("overflow", "hidden");
    dialog.kendoGrid($.fn.LookupPrepareGrid(listrole));
    var buttonPlace = dialog.parent().parent().find(".ui-dialog-buttonpane");
    if ($("#LookupcmdNew").length == 0) {
        buttonPlace.append("<input type='button' id='LookupcmdNew' value='" + cap_MyProfileCmdNew + "' class='newButtonInGridDialog' data-listrole='" + listrole + "' data-itemrole='" + itemrole + "'/>");
        $("#LookupcmdNew").button();
    }
    $("#LookupcmdNew").on("click", $.fn.LookupNewClick);
}

$.fn.LookupNewClick = function (evt, ui) {
    /// <summary>
    /// Create form create a new Lookup element
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var listrole = $("#LookupDialogGridDiv").data("listrole");
    var itemrole = $("#LookupDialogGridDiv").data("itemrole");
    evt.preventDefault();
    LookupDetailFeed_JSonModel.ItemToFeedId = -1;
    LookupDetailFeed_JSonModel.UserId = ForUserId;
    LookupDetailFeed_JSonModel.ItemType = itemrole;
    LookupDetailFeed_JSonModel.HtmlElementToUpdate = "#LookupDetailDialogDiv";
    var dialogTitle = eval("cap_EtyName_" + itemrole);
    $.fn.jqDialogFunction("LookupDetailDialogDiv", dialogTitle, $.fn.LookupAddEditItemOkClick, $.fn.LookupDetailCancelClick, $.fn.LookupDetailFeed, dlgLookupFormWidth, dlgLookupFormHeight, "<div id='LookupDetailFormDiv' data-itemrole='" + itemrole + "'></div>", false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.LookupEdtClick = function (evt, ui) {
    /// <summary>
    /// Create form edit an existing Lookup element
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var listrole = $("#LookupDialogGridDiv").data("listrole");
    var itemrole = $("#LookupDialogGridDiv").data("itemrole");
    evt.preventDefault();
    //var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    LookupDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    LookupDetailFeed_JSonModel.UserId = ForUserId;
    LookupDetailFeed_JSonModel.ItemType = itemrole;
    LookupDetailFeed_JSonModel.HtmlElementToUpdate = "#LookupDetailDialogDiv";
    var dialogTitle = eval("cap_EtyName_" + itemrole);
    $.fn.jqDialogFunction("LookupDetailDialogDiv", dialogTitle, $.fn.LookupAddEditItemOkClick, $.fn.LookupDetailCancelClick, $.fn.LookupDetailFeed, dlgLookupFormWidth, dlgLookupFormHeight, "<div id='LookupDetailFormDiv' data-itemrole='" + itemrole + "'></div>", false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.LookupAddEditItemOkClick = function (evt, ui) {
    /// <summary>
    /// Add or Edit lookup form Ok handler
    /// </summary>
    var listrole = $("#LookupDialogGridDiv").data("listrole");
    var itemrole = $("#LookupDialogGridDiv").data("itemrole");
    evt.preventDefault();
    var form = $(this).parent().find("form");
    form.attr("action", "/Lookups/Lookup" + itemrole + "AddEdit/" + uiLanguage);
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

$.fn.LookupDetailCancelClick = function (evt, ui) {
    /// <summary>
    /// Lookup cancel button handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    $("#LookupDetailDialogDiv").dialog("close");
    $.fn.EnsureStopPropagation(evt);
}

$.fn.LookupDetailFeed = function (evt, ui) {
    /// <summary>
    /// Request Lookup element form
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    $("#LookupDetailDialogDiv").append(waitImage);
    var listrole = $("#LookupDialogGridDiv").data("listrole");
    var itemrole = $("#LookupDialogGridDiv").data("itemrole");
    var ajaxData = JSON.stringify(LookupDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/Lookups/Get/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.LookupDetailBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.LookupDetailBuild = function (a, b, c) {
    /// <summary>
    /// Build Lookup element form
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b">usually unused</param>
    /// <param name="c">usually unused</param>
    if (a.success) {
        CurrentCompetencyChanged = false;
        $(a.domElementToUpdate).html(a.htmlContent);
        var form = $("#frmLookupDetail");
        form.attr("action", "/Lookup/LookupAddEdit/" + uiLanguage);
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.LookupDeleteClick = function (evt, ui) {
    /// <summary>
    /// Delete a lookup element (if possible)
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    var listrole = $("#LookupDialogGridDiv").data("listrole");
    var itemrole = $("#LookupDialogGridDiv").data("itemrole");
    evt.preventDefault();
    //var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    LookupDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    LookupDetailFeed_JSonModel.ItemType = itemrole;
    LookupDetailFeed_JSonModel.HtmlElementToUpdate = "#dialogMessage";
    $.fn.jqDialogConfirm(cap_MyPrettyCMS_MessageTitle, cap_ConfirmRemovingElement, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.LookupDelete, null, null);
    $.fn.EnsureStopPropagation(evt);

}

$.fn.LookupDelete = function () {
    ///<summary>
    ///X to delete a lookup element
    ///</summary>
    var ajaxData = JSON.stringify(LookupDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/Lookups/Delete/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailCompetencyDeleted,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });

}

$.fn.LookupUpdate = function (reloadGridPage, dialogToClose) {
    /// <summary>
    ///Called by MainAjaxSuccess when a lookup element is updated or deleted
    /// </summary>
    /// <param name="reloadGridPage"></param>
    /// <param name="dialogToClose"></param>
    if (reloadGridPage) {
        $.fn.LookupBuildGrid();
    }
    if (dialogToClose != null) {
        $(dialogToClose).dialog("close");
    }
}

$.fn.LookupPrepareGrid = function (tableName) {
    /// <summary>
    /// Prepare datasource to build a grid for a lookup
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns type="KendoUIWeb grid conf parameters object"></returns>
    var toReturn = {
        dataSource: $.fn.LookupPrepareDataSource(tableName),
        filterable: true,
        sortable: true,
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "Id",
                filterable: false,
                hidden: true
            },
            {
                field: "Name",
                title: Ety_v_Competencies_Name,
                filterable: true,
                width: 100,
                template: "<span class='dataId' data-id='#= Id #'>#= Name #</span>"
            },
            {
                field: "Description",
                title: Ety_v_Competencies_Description,
                filterable: true,
                width: 150
            },
            {
                command: {
                    name: "edt",
                    click: $.fn.LookupEdtClick
                },
                title: "",
                width: 85
            },
            {
                command: {
                    name: "X",
                    click: $.fn.LookupDeleteClick
                },
                title: "",
                width: 85
            }
        ]
    };
    return toReturn;
}

$.fn.LookupPrepareDataSource = function (tableName) {
    /// <summary>
    /// Prepare MyProfile Addresses grid data source
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns type=""></returns>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/" + tableName.toLowerCase(),
                dataType: "json",
                cache: false
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    Id: { type: "number" },
                    Name: { type: "string" },
                    Description: { type: "string" }
                }
            }
        }
    });
    return toReturn;
}

$.fn.jqDialogClosing = function (dialogSelector) {
    ///<summary>
    ///Must be used to close dialogs
    ///</summary>
    ///<param name="dialogSelector" type="String">
    /// JQuerySelector id or class
    ///</param>
    dialogCounter--;
}

$.fn.jqDialogPrepareAndGet = function (dialogId, innerHtml) {
    ///<summary>
    ///Generate or regenerate a div to display a menu
    ///</summary>
    ///<param name="dialogId" type="String">
    /// The id of the div to be transformed to a dialog box
    ///</param>
    ///<param name="innerHtml" type="String">
    /// Html to append in the content div
    ///</param>
    ///<param name="displayWaitIcon" type="String">
    /// Display wait icon ONLY IF innerHtml IS EMPTY !!!
    ///</param>
    if (dialogId.substr(0, 1) == "#") {
        dialogId = dialogId.substr(1);
    }
    var dialog = $("#" + dialogId);
    if (dialog.length > 0) {
        dialog.remove();
    }
    var dialogHtml = "";
    dialogHtml += "<div id='" + dialogId + "' class='innoUI' >";
    if (innerHtml != undefined && innerHtml.length > 0) {
        dialogHtml += innerHtml;
    }
    dialogHtml += "</div>";
    $('body').append(dialogHtml);
    dialogCounter++;
    return $("#" + dialogId);
}

$.fn.PrepareLayoutMenus = function () {
    ///<summary>
    ///Prepare drop down menus
    ///</summary>
    $.fn.SiteLayoutPrepareMenu(); //---> in head section of the current layout
    $("#divMyAccountBalloon").find("ul").kendoMenu({
        open: $.fn.KendoMenuOpenFixup
    });
    var contents = $("#divMyAccountBalloon").clone().attr("id", "divUsernameBalloon").removeClass("notDisplayed");
    $(".username").balloon({ position: "bottom", contents: contents });//contents, classname: "usernameBalloon" });
    $(".username").on("click", $.fn.MyProfileDialogOpenClick);
}

jQuery(function ($) {
    /// <summary>
    /// French localization for datepicker
    /// </summary>
    if ($.datepicker != null) {
        $.datepicker.regional['fr'] = {
            clearText: 'Effacer', clearStatus: '',
            closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
            prevText: '<Préc', prevStatus: 'Voir le mois précédent',
            nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
            currentText: 'Courant', currentStatus: 'Voir le mois courant',
            monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
		'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
            monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun',
		'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'],
            monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
            weekHeader: 'Sm', weekStatus: '',
            dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
            dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
            dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
            dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
            dateFormat: 'dd/mm/yy', firstDay: 0,
            initStatus: 'Choisir la date', isRTL: false
        };
        $.datepicker.setDefaults($.datepicker.regional['fr']);
    }
});

/*#endregion*/

$.fn.ToggleDisplayText = function () {
    /// <summary>
    /// Display text or * in password fields
    /// </summary>
    var currentType = $('#pwdOldPassword').get(0).type;
    if (currentType == "password") {
        $('#pwdOldPassword').get(0).type = "text";
        $('#pwdNewPassword').get(0).type = "text";
        $('#pwdRetypePassword').get(0).type = "text";
    } else {
        $('#pwdOldPassword').get(0).type = "password";
        $('#pwdNewPassword').get(0).type = "password";
        $('#pwdRetypePassword').get(0).type = "password";
    }
}


/*#region MyProfileManagement*/
$.fn.MyProfileDialogOpenClick = function (evt, ui) {
    ///<summary>
    ///Open MyProfile View in a pop up
    ///</summary>
    $.fn.jqDialogFunction("dialogMyProfile", cap_DialogMyProfileTitle, $.fn.MyProfile_Save, $.fn.MyProfile_Cancel, $.fn.MyProfile_Load, 785, 660, null, false, true);
}

$.fn.MyProfile_Load = function () {
    ///<summary>
    ///Ajax call back to load my profile view in dialog
    ///</summary>
    MyProfileFeed_JSonModel.HtmlElementToUpdate = "#dialogMyProfile";
    $("#dialogMyProfile").append(waitImage);
    var ajaxData = JSON.stringify(MyProfileFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/GetCurrentUserProfile/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.MyProfileDisplayCurrent,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.MyProfileDisplayCurrent = function (a, b, c) {
    ///<summary>
    ///MyProfile display callback success function
    ///</summary>
    if (a.success) {
        ForUserId = a.additionalData.forUserId;
        CurrentAddressChanged = false;
        CurrentTelecomChanged = false;
        CurrentCompetencyChanged = false;
        $(a.domElementToUpdate).html(a.htmlContent);
        $(".datePickUp").datepicker();
        var form = $("#frmMyProfile");
        $(".MyProfileAddressButton").button();
        $("#cmdMyProfileAddressAction").on("click", $.fn.ProfileDetailAddressOkClick);
        $("#cmdMyProfileAddressCancelAction").on("click", $.fn.MyProfileAddressCancelClick);
        $("#chkDisplayText").on("click", $.fn.ToggleDisplayText);
        var iconUploadDialogOpenButton = $("#UserProfileIconImgUploadButton");
        iconUploadDialogOpenButton.on("click", $.fn.ProfileDetailUserIconUploadDialogOpenClick);
        $.fn.ProfileDetailPrepareButtons(a.additionalData.modelToFeed.Contact.FK_InnoAppUser, "dialogMyProfile");
        //Map
        $.fn.GoogleMapConfiguration(a.additionalData.modelToFeed.Contact.IconPath);
    } else {
        $.fn.jqDialogAlert(cap_DialogErrorTitle, a.message);
    }
}

$.fn.ProfileDetailUserIconUploadDialogOpenClick = function (evt, ui) {
    var form = $("#SingleFileUploadForm");
    form.on("submit", $.fn.UserProfileUploadUserDialogClose);
    var iconUploadDialogOpenButton = $("#UserProfileIconImgUploadButton");
    iconUploadDialogOpenButton.button();
    $("#SingleFileUploadImageToUpdateIdHidden").val("#UserProfileIconImg");
    $("#SingleFileUploadFileInput").button();
    $.fn.SingleFileUploadDialogOpen("UploadUserIcon");
}

$.fn.SingleFileUploadDialogOpen = function (formAction) {
    var uploadWindow = $("#SingleFileUploadDialogDiv");
    $("#SingleFileUploadForm").attr("action", "/SingleFileUpload/" + formAction);
    uploadWindow.dialog({
        height: 110,
        width: 410,
        title: cap_MyProfile_UploadUserIconDialogTitle,
        resizable: false,
        autoOpen: true,
        open: $.fn.UserProfileUploadUserDialogOpen,
        close: $.fn.UserProfileUploadUserDialogClose
    });
    $("#SingleFileUploadSubmitButton").button();

}

$.fn.ProfileDetailAddressOkClick = function (evt, ui) {
    alert("ToDo");
}

$.fn.ProfileDetailPrepareButtons = function (forUserId, parentDialogId) {
    $("#" + parentDialogId).find(".cmdCompetencies").attr("value", cap_MyProfileCmdCompetencies);
    $("#" + parentDialogId).find(".cmdTelecoms").attr("value", cap_MyProfileCmdTelecoms);
    $("#" + parentDialogId).find(".cmdAddresses").attr("value", cap_MyProfileCmdAddresses);
    $("#" + parentDialogId).find(".cmdChangePassword").attr("value", cap_MyProfileCmdChangePassword);

    if (forUserId != undefined && forUserId != null && forUserId != "") {
        ForUserId = forUserId;
    } else {
        ForUserId = "";
    }

    $("#" + parentDialogId).find(".cmdCompetencies").on("click", $.fn.ProfileDetailCompetenciesOpenDialogClick);
    $("#" + parentDialogId).find(".cmdTelecoms").on("click", $.fn.ProfileDetailTelecomsOpenDialogClick);
    $("#" + parentDialogId).find(".cmdAddresses").on("click", $.fn.ProfileDetailAddressesOpenDialogClick);
    $("#" + parentDialogId).find(".cmdChangePassword").on("click", $.fn.ProfileChangePasswordClick);
    $(".ContactDetailsButton").button();

}

/*#region Change Password*/
$.fn.ProfileChangePasswordClick = function (evt, ui) {
    /// <summary>
    /// Prepare and open MyProfile competencies dialog
    /// </summary>
    $.fn.jqDialogFunction("ProfilePasswordChangeDialog", cap_MyProfileCmdChangePassword, $.fn.ProfilePasswordChangeClick, null, $.fn.ProfilePasswordChangeFeed, dlgChangePasswordWidth, dlgChangePasswordHeight, null, false);
}

$.fn.ProfilePasswordChangeFeed = function () {
    $("#ProfilePasswordChangeDialog").append(waitImage);
    Simple_JSonModel.HtmlElementToUpdate = "#ProfilePasswordChangeDialog";
    var ajaxData = JSON.stringify(Simple_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/ChangePassword/Feed/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfilePasswordChangeBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfilePasswordChangeBuild = function (a, b, c) {
    if (a.success) {
        $(a.domElementToUpdate).html(a.htmlContent);
        $(a.domElementToUpdate).find("#chkDisplayText").on("click", $.fn.ToggleDisplayText);
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfilePasswordChangeClick = function (evt, ui) {

}

/*#endregion*/
/*#region MyProfile Competencies*/

$.fn.ProfileDetailCompetenciesOpenDialogClick = function (evt, ui) {
    /// <summary>
    /// Prepare and open MyProfile competencies dialog
    /// </summary>
    $.fn.jqDialogContainer("ProfileDetailCompetenciesGridDialog", cap_MyProfileCmdCompetencies, $.fn.ProfileDetailCompetenciesGridBuild, null, 605, 545, "<div id='ProfileDetailCompetenciesGridDiv'></div>");
}

$.fn.ProfileDetailCompetenciesPrepareDataSource = function () {
    /// <summary>
    /// Prepare MyProfile competencies grid data source
    /// </summary>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/contactcompetencies?$filter=UserId eq guid'" + ForUserId + "'",
                dataType: "json",
                cache: false
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    Id: { type: "number" },
                    CompetencyName: { type: "string" },
                    YearsOfExperience: { type: "number" },
                    SortIndex: { type: "number" }
                }
            }
        }
    });
    return toReturn;
}

$.fn.ProfileDetailCompetenciesPrepareGrid = function () {
    var ItemType = "Competency";
    var toReturn = {
        dataSource: $.fn.ProfileDetailCompetenciesPrepareDataSource(),
        filterable: true,
        sortable: true,
        //selectable:true, ToDo LJO : but keep selection when change order
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "Id",
                filterable: false,
                hidden: true
            },
            {
                field: "CompetencyName",
                title: Ety_v_ContactCompetencies_CompetencyName,
                filterable: true,
                width: 300
            },
            {
                field: "YearsOfExperience",
                title: Ety_v_ContactCompetencies_YearsOfExperience,
                filterable: true,
                width: 45
            },
            {
                field: "SortIndex",
                title: "",
                filterable: false,
                width: 45,
                template: $.fn.KendoReorderColumnTemplate(ItemType)
            },
            {
                command: {
                    name: "edt",
                    click: $.fn.ProfileDetailCompetencyEdtClick
                },
                title: "",
                width: 85
            },
            {
                command: {
                    name: "X",
                    click: $.fn.ProfileDetailCompetencyDeleteClick
                },
                title: "",
                width: 85
            }
        ]
    };
    return toReturn;
}

$.fn.ProfileDetailCompetenciesGridBuild = function () {
    /// <summary>
    /// Build MyProfile Competencies grid
    /// </summary>
    var gridSelector = "#ProfileDetailCompetenciesGridDiv";
    var grid = $(gridSelector);
    grid.kendoGrid($.fn.ProfileDetailCompetenciesPrepareGrid());
    grid.css("overflow", "hidden");
    grid.find(".ui-icon-circle-triangle-n").on("click", $.fn.ProfileDetailGridMoveRowUp);
    grid.find(".ui-icon-circle-triangle-s").on("click", $.fn.ProfileDetailGridMoveRowDwn);
    $('gridSelector tbody .k-grouping-row:contains("SortIndex")').hide();
    var dialog = $("#ProfileDetailCompetenciesGridDialog");
    var buttonPlace = dialog.parent().find(".ui-dialog-buttonpane");
    if ($("#MyProfileDetailCompetenciesCmdNew").length == 0) {
        buttonPlace.append("<input type='button' id='MyProfileDetailCompetenciesCmdNew' value='" + cap_MyProfileCmdNew + "' class='newButtonInGridDialog'/>");
        $("#MyProfileDetailCompetenciesCmdNew").button();
    }
    $("#MyProfileDetailCompetenciesCmdNew").on("click", $.fn.ProfileDetailCompetencyNewClick);
}

$.fn.ProfileDetailCompetencyNewClick = function (evt, ui) {
    /// <summary>
    /// Profile detail competency new handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    evt.preventDefault();
    ProfileDetailFeed_JSonModel.ItemToFeedId = -1;
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailCompetencyDialog";
    $.fn.jqDialogFunction("ProfileDetailCompetencyDialog", cap_ProfileDetail_Competency, $.fn.ProfileDetailCompetencyAddEdit, null, $.fn.ProfileDetailCompetencyFeed, dlgCompetencyWidth, dlgCompetencyHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailCompetencyEdtClick = function (evt, ui) {
    /// <summary>
    /// Competencies grid Edt button handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    evt.preventDefault();
    //var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailCompetencyDialog";
    $.fn.jqDialogFunction("ProfileDetailCompetencyDialog", cap_ProfileDetail_Competency, $.fn.ProfileDetailCompetencyAddEdit, null, $.fn.ProfileDetailCompetencyFeed, dlgCompetencyWidth, dlgCompetencyHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailCompetencyFeed = function (evt) {
    $("#ProfileDetailCompetencyDialog").append(waitImage);
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailCompetencyGet/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailCompetencyBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfileDetailCompetencyBuild = function (a, b, c) {
    ///<summary>
    ///Profile detail callback success function
    ///</summary>
    if (a.success) {
        ForUserId = a.additionalData.forUserId;
        CurrentCompetencyChanged = false;
        $(a.domElementToUpdate).html(a.htmlContent);
        $("#cmdEditCompetencies").data("listrole", "Competencies");
        $("#cmdEditCompetencies").data("itemrole", "Competency");
        $("#cmdEditCompetencies").data("onclose", "$.fn.ProfileDetailCompetencyFeed");
        $("#cmdEditCompetencies").on("click", $.fn.LookupDialogOpenClick);
        var dialogSelector = "#ProfileDetailCompetencyDialog";
        var dialog = $(dialogSelector);
        var form = dialog.find("#frmProfileDetailCompetency");
        form.attr("action", "/MyProfile/ProfileDetailCompetencyAddEdit/" + uiLanguage);
        form.find("#DialogToClose").val(dialogSelector);
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfileDetailCompetencyDeleteClick = function (evt, ui) {
    ///<summary>
    ///Ask Profile competency delete
    ///</summary>
    evt.preventDefault();
    var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".kendoGridReorder").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#dialogMessage";
    $.fn.jqDialogConfirm(cap_MyPrettyCMS_MessageTitle, cap_ConfirmRemovingElement, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.ProfileDetailCompetencyDelete, null, null);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailCompetencyAddEdit = function (evt, ui) {
    ///<summary>
    ///Click ok for add or edit PorileDetailCompetency
    ///</summary>
    var form = $(this).parent().find("form");
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

$.fn.ProfileDetailCompetencyDelete = function (evt, ui) {
    ///<summary>
    ///Click X to detach a competency form ProfileDetail
    ///</summary>
    evt.preventDefault();
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailCompetencyDelete/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailCompetencyDeleted,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfileDetailCompetencyDeleted = function (a, b, c) {
    ///<summary>
    ///ProfileDetailCompetencyDeleted response handling
    ///</summary>
    if (a.success) {
        if (a.scriptToExecute != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
            eval(a.scriptToExecute);
        }
    } else {
        if (a.domElementToUpdate != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
        }
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfileDetailCompetencyUpdate = function (reloadGridPage, dialogToClose) {
    ///<summary>
    ///Called by MainAjaxSuccess when Contact competency updated
    ///</summary>
    if (reloadGridPage) {
        $.fn.ProfileDetailCompetenciesGridBuild();
    }
    if (dialogToClose != null) {
        $(dialogToClose).dialog("close");
    }
}



/*#endregion*/

/*#region MyProfile Telecoms*/
$.fn.ProfileDetailTelecomsOpenDialogClick = function (evt, ui) {
    /// <summary>
    /// Prepare and open MyProfile Telecoms dialog
    /// </summary>
    $.fn.jqDialogContainer("ProfileDetailTelecomsGridDialog", cap_MyProfileCmdTelecoms, $.fn.ProfileDetailTelecomsGridBuild, null, 850, 460, "<div id='ProfileDetailTelecomsGridDiv'></div>");
}

$.fn.ProfileDetailTelecomsPrepareDataSource = function () {
    /// <summary>
    /// Prepare MyProfile Telecoms grid data source
    /// </summary>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/contacttelecoms?$filter=UserId eq guid'" + ForUserId + "'",
                dataType: "json",
                cache: false
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    Id: { type: "number" },
                    TelecomType: { type: "string" },
                    Value: { type: "string" },
                    SortIndex: { type: "number" }
                }
            }
        }
    });
    return toReturn;
}

$.fn.ProfileDetailTelecomsPrepareGrid = function () {
    var itemType = "Telecom";
    var toReturn = {
        dataSource: $.fn.ProfileDetailTelecomsPrepareDataSource(),
        filterable: true,
        sortable: true,
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "Id",
                filterable: false,
                hidden: true
            },
            {
                field: "TelecomType",
                title: Ety_v_ContactTelecoms_TelecomType,
                filterable: true,
                width: 200
            },
            {
                field: "Value",
                title: Ety_v_ContactTelecoms_Value,
                filterable: true,
                width: 365
            },
            {
                field: "SortIndex",
                title: "&nbsp;",
                filterable: false,
                width: 45,
                template: $.fn.KendoReorderColumnTemplate(itemType)
            },
            {
                command: {
                    name: "edt",
                    click: $.fn.ProfileDetailTelecomEdtClick
                },
                title: "",
                width: 85
            },
            {
                command: {
                    name: "X",
                    click: $.fn.ProfileDetailTelecomDeleteClick
                },
                title: "",
                width: 85
            }
        ]
    };
    return toReturn;
}

$.fn.ProfileDetailTelecomsGridBuild = function () {
    /// <summary>
    /// Build MyProfile Telecoms grid
    /// </summary>
    var gridSelector = "#ProfileDetailTelecomsGridDiv";
    var grid = $(gridSelector);
    grid.kendoGrid($.fn.ProfileDetailTelecomsPrepareGrid());
    grid.css("overflow", "hidden");
    grid.find(".ui-icon-circle-triangle-n").on("click", $.fn.ProfileDetailGridMoveRowUp);
    grid.find(".ui-icon-circle-triangle-s").on("click", $.fn.ProfileDetailGridMoveRowDwn);
    $('gridSelector tbody .k-grouping-row:contains("SortIndex")').hide();
    var dialog = $("#ProfileDetailTelecomsGridDialog");
    var buttonPlace = dialog.parent().find(".ui-dialog-buttonpane");
    if ($("#MyProfileDetailTelecomsCmdNew").length == 0) {
        buttonPlace.append("<input type='button' id='MyProfileDetailTelecomsCmdNew' value='" + cap_MyProfileCmdNew + "' class='newButtonInGridDialog'/>");
        $("#MyProfileDetailTelecomsCmdNew").button();
    }
    $("#MyProfileDetailTelecomsCmdNew").on("click", $.fn.ProfileDetailTelecomNewClick);
}

$.fn.ProfileDetailTelecomNewClick = function (evt, ui) {
    /// <summary>
    /// Add telecom button event handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    evt.preventDefault();
    ProfileDetailFeed_JSonModel.ItemToFeedId = -1;
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailTelecomDialog";
    $.fn.jqDialogFunction("ProfileDetailTelecomDialog", cap_ProfileDetail_Telecom, $.fn.ProfileDetailTelecomAddEdit, null, $.fn.ProfileDetailTelecomFeed, dlgTelecomWidth, dlgTelecomHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailTelecomEdtClick = function (evt, ui) {
    /// <summary>
    /// Telecoms grid Edt button handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    evt.preventDefault();
    //var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailTelecomDialog";
    $.fn.jqDialogFunction("ProfileDetailTelecomDialog", cap_ProfileDetail_Telecom, $.fn.ProfileDetailTelecomAddEdit, null, $.fn.ProfileDetailTelecomFeed, dlgTelecomWidth, dlgTelecomHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}


$.fn.ProfileDetailTelecomDeleteClick = function (evt, ui) {
    ///<summary>
    ///Ask Profile Telecom delete
    ///</summary>
    evt.preventDefault();
    var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".kendoGridReorder").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#dialogMessage";
    $.fn.jqDialogConfirm(cap_MyPrettyCMS_MessageTitle, cap_ConfirmRemovingElement, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.ProfileDetailTelecomDelete, null, null);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailTelecomDelete = function (evt, ui) {
    ///<summary>
    ///Click X to detach a Telecom form ProfileDetail
    ///</summary>
    evt.preventDefault();
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailTelecomDelete/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailTelecomDeleted,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfileDetailTelecomDeleted = function (a, b, c) {
    ///<summary>
    ///ProfileDetailTelecomDeleted response handling
    ///</summary>
    if (a.success) {
        if (a.scriptToExecute != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
            eval(a.scriptToExecute);
        }
    } else {
        if (a.domElementToUpdate != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
        }
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfileDetailTelecomUpdate = function (reloadGridPage, dialogToClose) {
    ///<summary>
    ///Called by MainAjaxSuccess when Contact Telecom updated
    ///</summary>
    if (reloadGridPage) {
        $.fn.ProfileDetailTelecomsGridBuild();
    }
    if (dialogToClose != null) {
        $(dialogToClose).dialog("close");
    }
}



$.fn.ProfileDetailTelecomFeed = function (evt) {
    $("#ProfileDetailTelecomDialog").append(waitImage);
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailTelecomGet/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailTelecomBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}
$.fn.ProfileDetailTelecomBuild = function (a, b, c) {
    ///<summary>
    ///Profile detail callback success function
    ///</summary>
    if (a.success) {
        ForUserId = a.additionalData.forUserId;
        CurrentTelecomChanged = false;
        $(a.domElementToUpdate).html(a.htmlContent);
        $("#cmdEditTelecoms").data("listrole", "TelecomTypes");
        $("#cmdEditTelecoms").data("itemrole", "TelecomType");
        $("#cmdEditTelecoms").data("onclose", "$.fn.ProfileDetailTelecomFeed");
        $("#cmdEditTelecoms").on("click", $.fn.LookupDialogOpenClick);
        var dialogSelector = "#ProfileDetailTelecomDialog";
        var dialog = $(dialogSelector);
        var form = dialog.find("#frmProfileDetailTelecom");
        form.attr("action", "/MyProfile/ProfileDetailTelecomAddEdit/" + uiLanguage);
        form.find("#DialogToClose").val(dialogSelector);
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}
$.fn.ProfileDetailTelecomAddEdit = function (evt, ui) {
    ///<summary>
    ///Click ok for add or edit PorileDetailTelecom
    ///</summary>
    var form = $(this).parent().find("form");
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

/*#endregion*/

/*#region MyProfile Addresses*/
$.fn.ProfileDetailAddressesOpenDialogClick = function (evt, ui) {
    /// <summary>
    /// Prepare and open MyProfile Addresses dialog
    /// </summary>
    $.fn.jqDialogContainer("ProfileDetailAddressesGridDialog", cap_MyProfileCmdAddresses, $.fn.ProfileDetailAddressesGridBuild, null, 900, 460, "<div id='ProfileDetailAddressesGridDiv'></div>");
}

$.fn.ProfileDetailAddressesPrepareDataSource = function () {
    /// <summary>
    /// Prepare MyProfile Addresses grid data source
    /// </summary>
    var toReturn = new kendo.data.DataSource({
        type: "odata",
        serverPaging: true,
        serverSorting: true,
        pageSize: 10,
        transport:
        {
            read:
            {
                url: "/odata/contactaddresses?$filter=UserId eq guid'" + ForUserId + "'",
                dataType: "json",
                cache: false
            }
        },
        schema:
        {
            data: function (data) {
                return data["value"];
            },
            total: function (data) {
                return data["odata.count"];
            },
            model: {
                fields: {
                    Id: { type: "number" },
                    AddressLabel: { type: "string" },
                    Town: { type: "string" },
                    Country: { type: "string" },
                    IsCorrespondence: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: false
                    },
                    IsDelivery: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: false
                    },
                    IsBilling: {
                        type: "boolean",
                        parse: $.fn.KenduUINullableBoolColumnParser,
                        nullable: false
                    }
                }
            }
        }
    });
    return toReturn;
}

$.fn.ProfileDetailAddressesPrepareGrid = function () {
    var toReturn = {
        dataSource: $.fn.ProfileDetailAddressesPrepareDataSource(),
        filterable: true,
        sortable: true,
        pageable: { messages: { display: "{0:d0} - {1:d0} " + cap_KendoUIGrid_Pageable_Of + " {2:d0} " + cap_KendoUIGrid_Pageable_Elements } },
        columns: [
            {
                field: "Id",
                filterable: false,
                hidden: true
            },
            {
                field: "AddressLabel",
                title: Ety_v_ContactAddresses_AddressLabel,
                filterable: true,
                width: 150
            },
            {
                field: "Town",
                title: Ety_v_ContactAddresses_Town,
                filterable: true,
                width: 150
            },
            {
                field: "Country",
                title: Ety_v_ContactAddresses_Country,
                filterable: true,
                width: 150
            },
            {
                field: "IsCorrespondence",
                title: Ety_v_ContactAddresses_isCorrespondence,
                filterable: true,
                width: 55
            },
            {
                field: "IsBilling",
                title: Ety_v_ContactAddresses_isBilling,
                filterable: true,
                width: 55
            },
            {
                field: "IsDelivery",
                title: Ety_v_ContactAddresses_isDelivery,
                filterable: true,
                width: 55
            },
            {
                field: "SortIndex",
                title: Ety_v_ContactAddresses_SortIndex,
                filterable: false,
                template: "<div class='kendoGridReorder dataId' data-id='#= Id #'><span class='value'>#= SortIndex #</span><span class='ui-icon ui-icon-circle-triangle-n' onclick='$.fn.KendoMoveGridRow(\"MyProfile\" , \"ProfileDetailAddressMove\",#= Id #,-1, \"$.fn.ProfileDetailAddressUpdate(true,null)\")'></span><span class='ui-icon ui-icon-circle-triangle-s' onclick='$.fn.KendoMoveGridRow(\"MyProfile\" , \"ProfileDetailAddressMove\",#= Id #,1,\"$.fn.ProfileDetailAddressUpdate(true,null)\")'></span></div>",
                width: 45
            },
            {
                command: {
                    name: "edt",
                    click: $.fn.ProfileDetailAddressEdtClick
                },
                title: "",
                width: 85
            },
            {
                command: {
                    name: "X",
                    click: $.fn.ProfileDetailCompetencyAddressClick
                },
                title: "",
                width: 85
            }
        ]
    };
    return toReturn;
}

$.fn.ProfileDetailAddressesGridBuild = function () {
    /// <summary>
    /// Build MyProfile Addresses grid
    /// </summary>
    var gridSelector = "#ProfileDetailAddressesGridDiv";
    var grid = $(gridSelector);
    grid.kendoGrid($.fn.ProfileDetailAddressesPrepareGrid());
    grid.css("overflow", "hidden");
    grid.find(".ui-icon-circle-triangle-n").on("click", $.fn.ProfileDetailGridMoveRowUp);
    grid.find(".ui-icon-circle-triangle-s").on("click", $.fn.ProfileDetailGridMoveRowDwn);
    $('gridSelector tbody .k-grouping-row:contains("SortIndex")').hide();
    var dialog = $("#ProfileDetailAddressesGridDialog");
    var buttonPlace = dialog.parent().find(".ui-dialog-buttonpane");
    if ($("#ProfileDetailAddressesCmdNew").length == 0) {
        buttonPlace.append("<input type='button' id='ProfileDetailAddressesCmdNew' value='" + cap_MyProfileCmdNew + "' class='newButtonInGridDialog'/>");
        $("#ProfileDetailAddressesCmdNew").button();
    }
    $("#ProfileDetailAddressesCmdNew").on("click", $.fn.ProfileDetailAddressNewClick);
}

$.fn.ProfileDetailAddressNewClick = function (evt, ui) {
    evt.preventDefault();
    ProfileDetailFeed_JSonModel.ItemToFeedId = -1;
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailAddressDialog";
    $.fn.jqDialogFunction("ProfileDetailAddressDialog", cap_ProfileDetail_Address, $.fn.ProfileDetailAddEditAddress, null, $.fn.ProfileDetailAddressFeed, dlgAddressWidth, dlgAddressHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailAddEditAddress = function (evt, ui) {
    ///<summary>
    ///Click ok for add or edit PorileDetailAddress
    ///</summary>
    var form = $(this).parent().find("form");
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}

$.fn.ProfileDetailAddressFeed = function (evt) {
    $("#ProfileDetailAddressDialog").append(waitImage);
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailAddressGet/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailAddressBuild,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfileDetailAddressBuild = function (a, b, c) {
    ///<summary>
    ///Profile detail callback success function
    ///</summary>
    if (a.success) {
        ForUserId = a.additionalData.forUserId;
        CurrentAddressChanged = false;
        $(a.domElementToUpdate).html(a.htmlContent);
        $("#cmdEditAddresses").data("listrole", "Addresses");
        $("#cmdEditAddresses").data("itemrole", "Address");
        $("#cmdEditAddresses").data("onclose", "$.fn.ProfileDetailAddressFeed");
        $("#cmdEditAddresses").on("click", $.fn.LookupDialogOpenClick);

        $("#ContactAddress_Country").autocomplete({
            source: function (request, response) {

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/locapi/" + uiLanguage + "/country/CountryNameContains",
                    data: '"' + request.term + '"',
                    success: function (data) {
                        response(data);
                    }
                });
            }
        });

        var dialogSelector = "#ProfileDetailAddressDialog";
        var dialog = $(dialogSelector);
        var form = dialog.find("#frmProfileDetailAddress");
        form.attr("action", "/MyProfile/ProfileDetailAddressAddEdit/" + uiLanguage);
        form.find("#DialogToClose").val(dialogSelector);
    } else {
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfileDetailAddressEdtClick = function (evt, ui) {
    /// <summary>
    /// Addresses grid Edt button handler
    /// </summary>
    /// <param name="evt"></param>
    /// <param name="ui"></param>
    evt.preventDefault();
    //var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".dataId").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#ProfileDetailAddressDialog";
    $.fn.jqDialogFunction("ProfileDetailAddressDialog", cap_ProfileDetail_Address, $.fn.ProfileDetailAddressAddEdit, null, $.fn.ProfileDetailAddressFeed, dlgAddressWidth, dlgAddressHeight, null, false);
    $.fn.EnsureStopPropagation(evt);
}

$.fn.ProfileDetailAddressAddEdit = function (evt, ui) {
    ///<summary>
    ///Click ok for add or edit PorileDetailAddress
    ///</summary>
    var form = $(this).parent().find("form");
    $.validator.unobtrusive.parse(form);
    form.validate();
    if (form.valid()) {
        form.submit();
    }
}



$.fn.ProfileDetailAddressDeleteClick = function (evt, ui) {
    ///<summary>
    ///Ask Profile Address delete
    ///</summary>
    evt.preventDefault();
    var dataItem = this.dataItem($(evt.currentTarget).closest("tr"));
    var realId = $(evt.currentTarget).closest("tr").find(".kendoGridReorder").data("id");
    ProfileDetailFeed_JSonModel.ItemToFeedId = realId;// dataItem.Id; Fixup Kendo datasource refresh bug
    ProfileDetailFeed_JSonModel.UserId = ForUserId;
    ProfileDetailFeed_JSonModel.HtmlElementToUpdate = "#dialogMessage";
    $.fn.jqDialogConfirm(cap_MyPrettyCMS_MessageTitle, cap_ConfirmRemovingElement, cap_RemoveMenuItemConfirmOkButtonTitle, cap_RemoveMenuItemConfirmCancelButtonTitle, $.fn.ProfileDetailAddressDelete, null, null);
    $.fn.EnsureStopPropagation(evt);
}


$.fn.ProfileDetailAddressDelete = function (evt, ui) {
    ///<summary>
    ///Click X to detach a Address form ProfileDetail
    ///</summary>
    evt.preventDefault();
    var ajaxData = JSON.stringify(ProfileDetailFeed_JSonModel);
    $.ajax(
    {
        type: "POST",
        url: "/MyProfile/ProfileDetailAddressDelete/" + uiLanguage,
        data: ajaxData,
        contentType: "application/json",
        async: false,
        success: $.fn.ProfileDetailAddressDeleted,
        error: function (xhr, ajaxOptions, thrownError) {
            $.fn.jqDialogAlert(cap_DialogErrorTitle, xhr.responseText);
        }
    });
}

$.fn.ProfileDetailAddressDeleted = function (a, b, c) {
    ///<summary>
    ///ProfileDetailAddressDeleted response handling
    ///</summary>
    if (a.success) {
        if (a.scriptToExecute != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
            eval(a.scriptToExecute);
        }
    } else {
        if (a.domElementToUpdate != null) {
            try { $(a.domElementToUpdate).dialog("close"); } catch (e) { }
        }
        $.fn.AjaxResponseFailed(a);
    }
}

$.fn.ProfileDetailAddressUpdate = function (reloadGridPage, dialogToClose) {
    ///<summary>
    ///Called by MainAjaxSuccess when Contact Address updated
    ///</summary>
    if (reloadGridPage) {
        $.fn.ProfileDetailAddressesGridBuild();
    }
    if (dialogToClose != null) {
        $(dialogToClose).dialog("close");
    }
}
/*#endregion*/

$.fn.GoogleMapConfiguration = function (iconPath) {
    /// <summary>
    /// Configure google map and create a marker icon with path
    /// </summary>
    /// <param name="iconPath">The icon absolute url</param>
    var GoogleLat = $("#MyProfileLocLat");
    var GoogleLng = $("#MyProfileLocLng");
    var Lat = GoogleLat.val().replace(",", ".");
    var Lng = GoogleLng.val().replace(",", ".");
    var mapOptions = {
        zoom: 2,
        center: new google.maps.LatLng(Lat, Lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var container = $('#frmMyProfile #MyProfileForm_Location .MyProfileFormFields')[0];
    MyProfileMap = new google.maps.Map(container, mapOptions);

    if ($.isNumeric(Lat) && $.isNumeric(Lng)) {
        $.fn.GoogleMapCreateMarker(MyProfileMap, $("#Contact_FK_Genre").text()[$("#Contact_FK_Genre").val()] + " " + $("#Contact_FirstName").val() + " " + $("#Contact_LastName").val(), Lat, Lng, $.fn.GoogleMapBuildUserIcon(iconPath));
    }

    google.maps.event.addListener(MyProfileMap, 'click', function (evt) {
        var size = 1, offset = 1;
        var Lat = evt.latLng.lat();
        var Lng = evt.latLng.lng();
        $("#MyProfileLocLat").val(Lat);
        $("#MyProfileLocLng").val(Lng);
        if (MyProfileMapMarker == null || MyProfileMapMarker == undefined) {
            $.fn.GoogleMapCreateMarker(MyProfileMap, $("#Contact_FK_Genre").text()[$("#Contact_FK_Genre").val()] + " " + $("#Contact_FirstName").val() + " " + $("#Contact_LastName").val(), Lat, Lng, $.fn.GoogleMapBuildUserIcon($("#Contact_IconPath").val().spli('?')[0]));
        } else {
            MyProfileMapMarker.setPosition(new google.maps.LatLng(Lat, Lng));
            MyProfileMap.panTo(new google.maps.LatLng(Lat, Lng));
        }
    });
}

$.fn.GoogleMapBuildUserIcon = function (iconPath) {
    /// <summary>
    /// Add _google_ to the icon path to get the small one
    /// </summary>
    /// <param name="iconPath"></param>
    /// <returns type=""></returns>
    var toReturn = iconPath;
    var extPos = toReturn.lastIndexOf(".");
    toReturn = toReturn.substr(0, toReturn.length - (toReturn.length - extPos)) + "_google" + toReturn.substr(extPos);
    return toReturn;
}

$.fn.GoogleMapCreateMarker = function (map, title, Lat, Lng, icon) {
    /// <summary>
    /// Create a google map marker  
    /// </summary>
    /// <param name="map">Google Map Object</param>
    /// <param name="title">Marker title</param>
    /// <param name="Lat">Latitude</param>
    /// <param name="Lng">Longitude</param>
    /// <param name="icon">Icon absolute url</param>
    MyProfileMapMarker = new google.maps.Marker({
        position: new google.maps.LatLng(Lat, Lng),
        map: map,
        title: title,
        icon: icon
    });
}

$.fn.GoogleMapAddMultipleUserMarkers = function (map, locations) {
    /// <summary>
    /// Add multiple markers on a google map
    /// </summary>
    /// <param name="map">Google Map object</param>
    /// <param name="locations">marker array</param>
    for (i = 0; i < locations.length; i++) {
        $.fn.GoogleMapCreateMarker(map, locations[i][0], locations[i][1], locations[i][2], locations[i][3]);
    }
}


$.fn.UserProfileUploadUserDialogOpen = function () {
    /// <summary>
    /// UserProfileUploadUserDialog open handle
    /// </summary>
    $("#UserProfileIconImgUploadButton").hide();
}
$.fn.UserProfileUploadUserDialogClose = function () {
    /// <summary>
    /// UserProfileUploadUserDialog close handle
    /// </summary>
    $("#UserProfileIconImgUploadButton").show();
    var uploadWindow = $("#SingleFileUploadDialogDiv");
    uploadWindow.dialog("close");
}

$.fn.MyProfile_Save = function () {
    ///<summary>
    ///MyProfile save button click handle
    ///</summary>
    var form = $("#frmMyProfile");
    form.find(':input').removeClass("input-validation-error");
    ///Check witch fields must be validated
    var PwdOld = $("#pwdOldPassword");
    var PwdNew = $("#pwdNewPassword");
    PwdOld.removeClass("ignore");
    PwdNew.removeClass("ignore");
    if ((PwdOld.val() + PwdNew.val()) == '') {
        PwdOld.addClass("ignore");
        PwdNew.addClass("ignore");
    }
    $.validator.unobtrusive.parse(form);
    var settings = $.data(form[0], 'validator').settings;
    settings.ignore = ".ignore";
    $.validator.unobtrusive.parse(form);
    if (form.valid()) {
        //Transfert values to JSonModel ToDo : return to the Innovacall Framework principal... 
        MyProfileSave_JSonModel.FK_Genre = $("#Contact_FK_Genre").val();
        MyProfileSave_JSonModel.FirstName = $("#Contact_FirstName").val();
        MyProfileSave_JSonModel.LastName = $("#Contact_LastName").val();
        MyProfileSave_JSonModel.BirthDate = $("#Contact_BirthDate").val();
        MyProfileSave_JSonModel.FK_Language = $("#Contact_FK_Language").val();
        MyProfileSave_JSonModel.IconPath = $("#UserProfileIconImg").attr("src");
        MyProfileSave_JSonModel.GoogleMapLat = $("#MyProfileLocLat").val();
        MyProfileSave_JSonModel.GoogleMapLng = $("#MyProfileLocLng").val();
        var ajaxData = JSON.stringify(MyProfileSave_JSonModel);
        var url = "/api/myprofile/" + $("#hidLanguage").val();
        $.ajax(
            {
                type: "POST",
                url: url,
                data: ajaxData,
                contentType: "application/json",
                async: false,
                success: $.fn.MyProfileSaved,
                error: function (xhr, ajaxOptions, thrownError) {
                    $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
                }
            });
    } else {
        //alert("form NOT valid");
    }

}
$.fn.MyProfileSaved = function () {
    $("#dialogMyProfile").dialog("close");
}
$.fn.MyProfile_Cancel = function () {
    $(this).dialog("close");
}
$.fn.MyProfileBuildAdminRolesDisplayGrid = function () {
    /// <summary>
    /// Build MyProfile AdminRoles grid
    /// </summary>
    $("#MyProfileDivDialogSettingsAdminRolesGrid").css("overflow", "hidden");
    $("#MyProfileDivDialogSettingsAdminRolesGrid").kendoGrid($.fn.SettingsAdminRolesPrepareGrid());
}
/*#endregion*/


/*
$.fn.SelectedAddressId = function () {
    var selected = $("#ulContactAddressList").find(".ui-selected");
    var selectedId = selected.attr("data-value");
    return selectedId;
}

$.fn.MyProfileAddressCancelClick = function () {
    $.fn.displayAddress($.fn.SelectedAddressId());
}
*/

$.fn.NavigateTo = function (url) {
    /// <summary>
    /// Navigate to URL
    /// </summary>
    /// <param name="url"></param>
    window.location.href = url;
}

$.fn.WriteStatus = function (text, width, keep) {
    /// <summary>
    /// Create a red div to write debug info
    /// </summary>
    var cleanText = text.replace("\n", "<br/>");
    var w = 150;
    if (width != null) {
        w = width
    }
    var divStatus = $("#divStatus");
    if (divStatus.length == 0) {
        cp = $("body").append("<div id='divStatus' style='position:fixed;border:1px solid black;height:100px;width:" + w + "px;top:112px; right:0;background-color:red;'></div>");
    }
    try {
        var statusContent = "";
        if (keep) {
            statusContent = divStatus.html();
            statusContent += "<div>" + cleanText + "</div>";
        } else {
            statusContent = "<div>" + cleanText + "</div>";
        }
        divStatus.html(statusContent);
    } catch (e) { }
}

/*#region Dialog boxes*/

$.fn.jqDialog = function (idDiv, title, redirection, width, height) {
    ///<summary>
    /// Create a simple JQueryUI Dialog box
    ///</summary>
    ///<param name="idDiv" type="String">
    /// The id of the div to be transformed to a dialog box
    ///</param>
    ///<param name="title" type="String">
    /// The title of the dialog box
    ///</param>
    ///<param name="redirection" type="String">
    /// if this parameter is set ok buton navigate to redirection address
    ///</param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultDialogHeight)
    ///</param>
    if (width == null) { width = defaultDialogWidth; }
    if (height == null) { height = defaultDialogHeight; }
    var dialogBox = $.fn.jqDialogPrepareAndGet(idDiv, null);
    dialogBox.hide();
    dialogBox.dialog({
        title: title,
        autoOpen: false,
        resizable: false,
        modal: true,
        minHeight: height,
        minWidth: width,
        buttons: [
			{
			    text: "Ok",
			    click: function (evt, ui) {
			        if (redirection != null) {
			            if (redirection != "") {
			                $.fn.NavigateTo(redirection);
			            }
			        }
			        $(this).dialog("close");
			    }
			}
        ],
        close: $.fn.jqDialogClosing,
        open: function (event, ui) {
            dialogCounter++;
        },
        zIndex: dialogCounter
    });
}

$.fn.jqDialogContainer = function (idDiv, title, openFunction, closeFunction, width, height, innerHtml) {
    ///<summary>
    /// Create JQueryUI Dialog box with close button
    ///</summary>
    ///<param name="idDiv" type="String">
    /// The id of the div to be transformed to a dialog box (NO HEADING #)
    ///</param>
    ///<param name="openFunction" type="function">
    /// Function called to initialize dialog box
    ///</param>
    ///<param name="closeFunction" type="function">
    /// Function called to when dialog is closed 
    ///</param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultDialogHeight)
    ///</param>
    if (width == null) { width = defaultDialogWidth; }
    if (height == null) { height = defaultDialogHeight; }
    var dialogBox = $.fn.jqDialogPrepareAndGet(idDiv, innerHtml);
    cancelFunction = null ? function (evt, ui) { $(this).dialog("close"); } : eval(closeFunction)
    dialogBox.hide();
    dialogBox.dialog({
        title: title,
        autoOpen: false,
        resizable: false,
        modal: true,
        minHeight: height,
        minWidth: width,
        open: openFunction,
        close: $.fn.jqDialogClosing,
        buttons: [
			{
			    text: cap_Close,
			    click: function () {
			        $(this).dialog("close");
			    }
			}
        ],
        zIndex: dialogCounter
    });
    var form = dialogBox.find("form");
    if (form != null) {
        $.validator.unobtrusive.parse(form);
    }
    dialogBox.dialog('open');
}

$.fn.jqDialogFunction = function (idDiv, title, okFunction, cancelFunction, openFunction, width, height, innerHtml, keepDivContent, displayWaitIcon) {
    ///<summary>
    /// Create JQueryUI Dialog box with custom ok, cancel and open functions
    ///</summary>
    ///<param name="divSelector" type="String">
    /// The id of the div to be transformed to a dialog box
    ///</param>
    ///<param name="okFunction" type="function">
    /// Function called when Ok button clicked
    ///</param>
    ///<param name="cancelFunction" type="function">
    /// Function called when Cancel button clicked must call $.fn.CloseDialog (if cancelFunction is null, dialog box is closed)
    ///</param>
    ///<param name="openFunction" type="function">
    /// Function called to initialize dialog box
    ///</param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultDialogHeight)
    ///</param>
    if (width == null) { width = defaultDialogWidth; }
    if (height == null) { height = defaultDialogHeight; }
    var dialogBox;
    if (!keepDivContent) {
        dialogBox = $.fn.jqDialogPrepareAndGet(idDiv, innerHtml);
    } else {
        dialogBox = $("#" + idDiv);
    }
    if (cancelFunction == null) {
        cancelFunction = $.fn.jqDialogClose
    }
    dialogBox.hide();
    dialogBox.dialog({
        title: title,
        autoOpen: false,
        resizable: false,
        modal: true,
        minHeight: height,
        minWidth: width,
        open: openFunction,
        buttons: [
			{
			    text: cap_Ok,
			    click: okFunction
			}
            ,
            {
                text: cap_Cancel,
                click: cancelFunction
            }
        ],
        zIndex: dialogCounter
    });
    var form = dialogBox.find("form");
    if (form != null) {
        $.validator.unobtrusive.parse(form);
    }
    dialogBox.dialog('open');
}

$.fn.jqDialogConfirm = function (title, message, confirmButtonTitle, cancelButtonTitle, okFunction, height, width) {
    /// <summary>
    /// Simple confirmation dialog box
    /// </summary>
    /// <param name="title" type="String">
    /// Title of the dialog
    /// </param>
    /// <param name="message" type="String">
    /// Message to display
    /// </param>
    /// <param name="confirmButtonTitle" type="String">
    /// Confirm button title
    /// </param>
    /// <param name="cancelButtonTitle"type="String">
    /// Cancel button title
    /// </param>
    /// <param name="okFunction" type="function">
    /// Function called when Ok button clicked
    ///</param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultSmallDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultSmallDialogHeight)
    ///</param>
    if (width == null) { width = defaultSmallDialogWidth; }
    if (height == null) { height = defaultSmallDialogHeight; }
    var dialogBox = $.fn.jqDialogPrepareAndGet('dialogMessage', null);
    dialogBox.text(message);
    dialogBox.hide();
    dialogBox.dialog({
        title: title,
        autoOpen: false,
        resizable: false,
        modal: true,
        minHeight: height,
        minWidth: width,
        buttons: [
			{
			    text: confirmButtonTitle,
			    click: okFunction
			}
            ,
            {
                text: cancelButtonTitle,
                click: $.fn.jqDialogClose
            }
        ],
        zIndex: dialogCounter
    });
    dialogBox.dialog('open');
}

$.fn.jqDialogYesNoFunction = function (title, message, yesButtonTitle, noButtonTitle, yesFunction, noFunction, openFunction, width, height) {
    /// <summary>
    /// Yes / No JQuery UI dialog box
    /// </summary>
    /// <param name="title" type="String">
    /// Title of the dialog
    /// </param>
    /// <param name="message" type="String">
    /// Message to display
    /// </param>
    /// <param name="yesButtonTitle" type="String">
    /// Confirm button title
    /// </param>
    /// <param name="noButtonTitle"type="String">
    /// Cancel button title
    /// </param>
    /// <param name="yesFunction" type="function">
    /// Function called when yes button clicked
    /// </param>
    /// <param name="noFunction" type="function">
    /// Function called when no button clicked
    /// </param>
    /// <param name="openFunction" type="function">
    /// Function called to initialize dialog
    /// </param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultSmallDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultSmallDialogHeight)
    ///</param>
    if (width == null) { width = defaultSmallDialogWidth; }
    if (height == null) { height = defaultSmallDialogHeight; }
    var dialogBox = $.fn.jqDialogPrepareAndGet('divDialogMessage', null);
    dialogBox.text(message);
    dialogBox.hide();
    dialogBox.dialog({
        title: title,
        autoOpen: false,
        resizable: false,
        modal: true,
        width: width,
        height: height,
        open: openFunction,
        closeOnEscape: false,
        buttons: [
			{
			    text: yesButtonTitle,
			    click: yesFunction
			}
            ,
            {
                text: noButtonTitle,
                click: noFunction
            }
        ],
        zIndex: 3999
    });
    var form = dialogBox.find("form");
    if (form != null) {
        $.validator.unobtrusive.parse(form);
    }
    //$(".ui*").mouseout(function (e) { e.preventDefault()});
    dialogBox.dialog('open');
}

$.fn.jqDialogAlert = function (title, message, redirection, width, height) {
    /// <summary>
    /// Alert dialog box
    /// </summary>
    /// <param name="title" type="String">
    /// Title of the dialog
    /// </param>
    /// <param name="message" type="String">
    /// Message to display
    /// </param>
    /// <param name="redirection" type="String">
    /// Navigate to redirection address if not null
    /// </param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultSmallDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultSmallDialogHeight)
    ///</param>
    if (width == null) { width = defaultSmallDialogWidth; }
    if (height == null) { height = defaultSmallDialogHeight; }
    if (message.indexOf("<html>", 0) >= 0) {
        width = 800;
        height = 600;
    }
    $.fn.jqDialog('dialogMessage', title, redirection, width, height);
    $('#dialogMessage').html('');
    if (message.indexOf("<html>", 0) >= 0) {
        var iFrame = $("#dialogMessage").find(".ui-dialog-content").find("#AjaxErrorIFrame");
        $('#dialogMessage').html('');
        if (iFrame.length == 0) {
            iFrameHtml = "<iframe id='AjaxErrorIFrame' name='AjaxErrorIFrame' frameborder='0' scrolling='yes' style='width:" + (width - 20) + "px;height:" + (height - 50) + "px'>";
            $("#dialogMessage").html(iFrameHtml);
        }
        var doc = ($("#AjaxErrorIFrame")[0]).contentWindow;
        doc.document.open();
        doc.document.write(message);
        window.document.close();
    } else {
        $('#dialogMessage').text(message);
    }
    $('#dialogMessage').dialog('open');
}

$.fn.jqDialogAjaxError = function (title, message, redirection, width, height) {
    /// <summary>
    /// Display a dialog message completed with a IFrame to display a error message coming from server
    /// </summary>
    /// <param name="title" type="String">
    /// Title of the dialog
    /// </param>
    /// <param name="message" type="String">
    /// Message to display
    /// </param>
    /// <param name="redirection" type="String">
    /// Navigate to redirection address if not null
    /// </param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultDialogHeight)
    ///</param>
    if (width == null) { width = defaultDialogWidth; }
    if (height == null) { height = defaultDialogHeight; }
    $.fn.jqDialog('dialogMessage', title, redirection, width, height, false);
    var iFrame = $("#dialogMessage").find(".ui-dialog-content").find("#AjaxErrorIFrame");
    $('#dialogMessage').html('');
    if (iFrame.length == 0) {
        iFrame = $("<iframe id='AjaxErrorIFrame' name='AjaxErrorIFrame' frameborder='0' scrolling='yes' width='" + width + "' height='" + height - 50 + "'>");
        iFrameParent = $("#dialogMessage");
        iFrameParent.append(iFrame);
    }
    var doc = ($("#AjaxErrorIFrame")[0]).contentWindow;
    doc.document.open();
    doc.document.write(message);
    window.document.close();
    $('#dialogMessage').dialog('open');
}

$.fn.InlinePopup = function (url, title, width, height) {
    ///<summary>
    ///Create a popup window with a JQuery UI Dialog with a frame inside
    ///</summary>
    ///<param name="url" type="String">
    /// IFrame source URL
    ///</param>
    ///<param name="title" type="String">
    /// Title of the dialog
    ///</param>
    ///<param name="width" type="int">
    /// Width in pixels of the dialog box (default : defaultDialogWidth)
    ///</param>
    ///<param name="height" type="int">
    /// Height in pixels of the dialog box (default : defaultDialogHeight)
    ///</param>
    if (width == null) { width = defaultDialogWidth; }
    if (height == null) { height = defaultDialogHeight; }
    var IP = $.fn.jqDialogPrepareAndGet("#inlinePopup", "<iframe id='ifrInlinePopup' frameborder='0' scrolling='no'></iframe>");
    var IFR = $("#ifrInlinePopup");
    IFR.attr("src", url);
    IP.attr("title", title);
    IP.dialog({
        height: height,
        width: width,
        modal: true,
        resizable: false,
        close: $.fn.jqDialogClosing,
        closeOnEscape: true,
        zIndex: dialogCounter
    });
}

/*#endregion*/

$.fn.AjaxResponseFailed = function (a) {
    /// <summary>
    /// Ajax response success = false
    /// </summary>
    if (a.scriptToExecute != null) {
        eval(a.scriptToExecute);
    } else if (a.message != null) {
        $.fn.jqDialogAlert((a.messageTitle == "" ? cap_DialogErrorTitle : a.messageTitle), a.message, null, 300, 100);
    }
}

$.fn.EnsureStopPropagation = function (evt) {
    /// <summary>
    /// Ensure user action stop immediately
    /// Example : If you have a clickable element inside an other clickable element
    /// </summary>
    /// <param name="evt"></param>
    try {
        evt.preventDefault();
    } catch (ex) { }
    try {
        evt.stopPropagation();
    } catch (ex) { }
    try {
        evt.stopImmediatePropagation();
    } catch (ex) { }
}

$.fn.SerializeObject = function () {
    /// <summary>
    /// Serialize all controls of a form
    /// </summary>
    /// <returns type="object">the object</returns>
    var obj = {};
    $(":input[type='checkbox']").each(function (e) {
        obj[this.name] = this.checked;
    });
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (obj !== undefined) {
                if (obj[this.name] !== undefined) {
                    o[this.name] = obj[this.name];
                }
            }
            else {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            }
        }
        else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/*#region Unobstrusive Validation fixup*/
$.validator.methods.range = function (value, element, param) {
    /// <summary>
    /// Fixup range validator 
    /// </summary>
    /// <param name="value"></param>
    /// <param name="element"></param>
    /// <param name="param"></param>
    /// <returns type=""></returns>
    var globalizedValue = value.replace(",", ".");
    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}

$.validator.methods.number = function (value, element) {
    /// <summary>
    /// Fixup number validator
    /// </summary>
    /// <param name="value"></param>
    /// <param name="element"></param>
    /// <returns type=""></returns>
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
}

$.validator.methods.date = function (value, element) {
    /// <summary>
    /// Fixup date validator
    /// </summary>
    /// <param name="value"></param>
    /// <param name="element"></param>
    /// <returns type=""></returns>
    return this.optional(element) || Globalize.parseDate(value, "dd/MM/yyyy", "en");
}
/*#endregion*/

/*#region client components specific*/
$.fn.KendoMenuOpenFixup = function (e) {
    /// <summary>
    /// A fix for Kendo UI Menu
    /// </summary>
    /// <param name="e"></param>
    var evt = e;
}

$.fn.KenduUINullableBoolColumnParser = function (value) {
    ///<summary>
    ///A fix for Kendo UI grid for Nullble boolean column
    ///</summary>
    /// <param name="value">the nullable value</param>
    if (value != null) {
        return value || false;
    }
    return value;
}

$.fn.KendoDataSourceError = function (evt) {
    /// <summary>
    ///Displays dialog box to show kendo ui web datasource error
    /// </summary>
    /// <param name="evt"></param>
    var message = evt.status + "\n";
    message += evt.xhr.statusText + "\n";
    message += evt.xhr.responseText + "\n";
    $.fn.jqDialogAjaxError(cap_DialogMyProfileTitle, message);
}

$.fn.KendoReorderColumnTemplate = function (ItemType) {
    /// <summary>
    /// Prepare a template to reorder kendo grid rows
    /// </summary>
    /// <param name="ItemType"></param>
    /// <returns type=""></returns>
    return "<div class='kendoGridReorder dataId' data-id='#= Id #'><span class='value'>#= SortIndex #</span><span class='ui-icon ui-icon-circle-triangle-n' onclick='$.fn.KendoMoveGridRow(\"MyProfile\" , \"ProfileDetail" + ItemType + "Move\",#= Id #,-1, \"$.fn.ProfileDetail" + ItemType + "Update(true,null)\")'></span><span class='ui-icon ui-icon-circle-triangle-s' onclick='$.fn.KendoMoveGridRow(\"MyProfile\" , \"ProfileDetail" + ItemType + "Move\",#= Id #,1,\"$.fn.ProfileDetail" + ItemType + "Update(true,null)\")'></span></div>";
}

$.fn.KendoMoveGridRow = function (controller, action, itemId, direction, scriptToExecute) {
    /// <summary>
    /// Called to move an element in a Kendo UI Web grid
    /// ToDo LJO : See http://demos.kendoui.com/web/datasource/remote-operations.html to force sort by SortIndex
    /// </summary>
    /// <param name="controller"></param>
    /// <param name="action"></param>
    /// <param name="itemId"></param>
    /// <param name="direction"></param>
    /// <param name="scriptToExecute"></param>
    KendoGridElementMove_JSonModel.id = itemId;
    KendoGridElementMove_JSonModel.direction = direction;
    KendoGridElementMove_JSonModel.scriptToExecute = scriptToExecute;
    var ajaxData = JSON.stringify(KendoGridElementMove_JSonModel);
    var url = "/" + controller + "/" + action + "/" + uiLanguage;
    $.ajax(
        {
            type: "POST",
            url: url,
            data: ajaxData,
            contentType: "application/json",
            async: false,
            success: $.fn.MainAjaxSuccess,
            error: function (xhr, ajaxOptions, thrownError) {
                $.fn.jqDialogAjaxError(cap_DialogErrorTitle, (xhr.responseText));
            }
        });

}
/*#endregion*/


/*#region Advanced CSS Handling*/
$.fn.getStyleObject = function () {
    /// <summary>
    /// Get all css style of an object 
    /// </summary>
    /// <returns type=""></returns>
    var dom = this.get(0);
    var style;
    var returns = {};
    if (window.getComputedStyle) {
        var camelize = function (a, b) {
            return b.toUpperCase();
        }
        style = window.getComputedStyle(dom, null);
        for (var i = 0, l = style.length; i < l; i++) {
            var prop = style[i];
            var camel = prop.replace(/\-([a-z])/, camelize);
            var val = style.getPropertyValue(prop);
            returns[camel] = val;
        }
        return returns;
    }
    if (dom.currentStyle) {
        style = dom.currentStyle;
        for (var prop in style) {
            returns[prop] = style[prop];
        }
        return returns;
    }
    if (style = dom.style) {
        for (var prop in style) {
            if (typeof style[prop] != 'function') {
                returns[prop] = style[prop];
            }
        }
        return returns;
    }
    return returns;
}
/*#endregion*/